import {encode} from 'js-base64'
import request from "@/api/request"
import {file as fileConfig} from '@/config'
import store from '@/store'
import {isEmpty, timeFormat} from "@/util"
import {isExternal, isTxt} from "@/util/validate"

const defaultOptions = {
    headers: {"Content-Type": "multipart/form-data"},
    generateKey(filename) {
        return `${timeFormat('yyyy/MM/dd')}/user${store.state.user.id}/${Date.now()}/${filename}`
    }
}

//文件预览
export function preview(url) {
    if (isTxt(url)) return window.open(url)

    url = encodeURIComponent(encode(url))

    const anchor = document.createElement('a')
    anchor.style.display = 'none'
    url=autoCompleteUrl(url)
    // anchor.href='http://10.111.43.104/oss/avatar/aaaa.pdf'
    anchor.href=url
    // anchor.href = `${fileConfig.previewPrefix}/onlinePreview?url=${url}`
    anchor.target = '_blank'
    document.body.appendChild(anchor)
    anchor.click()
    document.body.removeChild(anchor)
}

//下载文件
export function download(name) {
  request.get(`http://10.111.43.104:8081/file/download?name=${name}`, { responseType: 'blob' })
    .then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', name);
      document.body.appendChild(link);
      link.click();
    });
}

// 头像上传
export function uploadImg(file) {
    return request.post('http://10.111.43.104:8081/file/uploadImg', {
        file: file
      }, 
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        withCredentials: true,
        crossDomain: true
      }
    )
}

// 文件上传
export function upload(file) {
    return request.post('http://10.111.43.104:8081/file/upload', {
        file: file
      }, 
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
      )
}


//自动补全附件链接前缀
export function autoCompleteUrl(url) {
    if (isEmpty(url)) return ''
    if (isExternal(url)) return url
    return fileConfig.storePrefix + url
}
